<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import DataTable from '@/components/DataTable.vue'
import DialogForm from '@/components/DialogForm.vue'
import { listStock, getStock, addStock, updateStock, delStock } from '@/api/stock'
import { listMedicine } from '@/api/medicine'

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  if (isNaN(date.getTime())) return dateTime;
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 表格数据
const tableData = ref([])
// 加载状态
const loading = ref(false)
// 药品列表
const medicineList = ref([])
// 表格列配置
const columns = [
  { 
    prop: 'medicineId', 
    label: '药品名称', 
    width: '180',
    formatter: (val) => {
      const medicine = medicineList.value.find(item => item.id === val)
      return medicine ? medicine.medicineName : ''
    }
  },
  { prop: 'quantity', label: '库存数量', width: '120' },
  { 
    prop: 'quantity', 
    label: '库存状态', 
    width: '120',
    formatter: (val) => {
      if (val <= 0) return '无库存'
      if (val < 10) return '库存不足'
      if (val < 50) return '库存正常'
      return '库存充足'
    }
  },
  { prop: 'lastUpdateTime', label: '最后更新时间', width: '180', formatter: (val) => formatDateTime(val) }
]
// 搜索字段
const searchFields = ['medicineId']

// 表单数据
const formData = reactive({
  id: null,
  medicineId: null,
  quantity: 0,
  lastUpdateTime: ''
})

// 表单字段配置 - 编辑模式
const editFormFields = ref([
  { 
    prop: 'medicineId', 
    label: '药品', 
    type: 'select', 
    required: true,
    options: []
  },
  { 
    prop: 'quantity', 
    label: '库存数量', 
    type: 'number', 
    required: true,
    min: 0,
    precision: 0
  }
])

// 表单字段配置 - 查看模式
const viewFormFields = ref([
  { 
    prop: 'medicineId', 
    label: '药品', 
    type: 'select', 
    disabled: true,
    options: []
  },
  { 
    prop: 'quantity', 
    label: '库存数量', 
    type: 'number', 
    disabled: true
  },
  { prop: 'lastUpdateTime', label: '最后更新时间', type: 'input', readonly: true }
])

// 表单规则
const formRules = {
  medicineId: [
    { required: true, message: '请选择药品', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存数量不能小于0', trigger: 'blur' }
  ]
}

// 对话框配置
const dialogConfig = reactive({
  visible: false,
  title: '添加库存',
  isEdit: false,
  isView: false
})

// 获取库存列表
const getStockList = async () => {
  loading.value = true
  try {
    tableData.value = await listStock()
  } catch (error) {
    console.error('获取库存列表失败', error)
    ElMessage.error('获取库存列表失败')
  } finally {
    loading.value = false
  }
}

// 获取药品列表
const getMedicineList = async () => {
  try {
    medicineList.value = await listMedicine()
    // 更新表单字段配置中的药品选项
    const medicineOptions = medicineList.value.map(item => ({
      label: item.medicineName,
      value: item.id
    }))
    
    // 更新药品选项
    editFormFields.value.find(item => item.prop === 'medicineId').options = medicineOptions
    viewFormFields.value.find(item => item.prop === 'medicineId').options = medicineOptions
  } catch (error) {
    console.error('获取药品列表失败', error)
    ElMessage.error('获取药品列表失败')
  }
}

// 添加库存
const handleAdd = () => {
  // 重置表单数据
  Object.keys(formData).forEach(key => {
    if (key === 'quantity') {
      formData[key] = 0
    } else {
      formData[key] = key === 'medicineId' ? null : ''
    }
  })
  formData.id = null
  
  dialogConfig.title = '添加库存'
  dialogConfig.isEdit = false
  dialogConfig.isView = false
  dialogConfig.visible = true
}

// 编辑库存
const handleEdit = async (row) => {
  try {
    const res = await getStock(row.id)
    if (res) {
      // 填充表单数据
      Object.keys(formData).forEach(key => {
        formData[key] = res[key] || ''
      })
      
      dialogConfig.title = '编辑库存'
      dialogConfig.isEdit = true
      dialogConfig.isView = false
      dialogConfig.visible = true
    }
  } catch (error) {
    console.error('获取库存详情失败', error)
    ElMessage.error('获取库存详情失败')
  }
}

// 查看库存
const handleView = async (row) => {
  try {
    const res = await getStock(row.id)
    if (res) {
      // 填充表单数据
      Object.keys(formData).forEach(key => {
        formData[key] = res[key] || ''
      })
      
      dialogConfig.title = '查看库存'
      dialogConfig.isEdit = false
      dialogConfig.isView = true
      dialogConfig.visible = true
    }
  } catch (error) {
    console.error('获取库存详情失败', error)
    ElMessage.error('获取库存详情失败')
  }
}

// 删除库存
const handleDelete = async (row) => {
  try {
    ElMessageBox.confirm('确定要删除该库存记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await delStock(row.id)
      ElMessage.success('删除成功')
      getStockList()
    }).catch(() => {})
  } catch (error) {
    console.error('删除库存失败', error)
    ElMessage.error('删除库存失败')
  }
}

// 批量删除库存
const handleBatchDelete = async (rows) => {
  try {
    ElMessageBox.confirm(`确定要删除选中的 ${rows.length} 条库存记录吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await Promise.all(rows.map(row => delStock(row.id)))
      ElMessage.success('批量删除成功')
      getStockList()
    }).catch(() => {})
  } catch (error) {
    console.error('批量删除库存失败', error)
    ElMessage.error('批量删除库存失败')
  }
}

// 提交表单
const handleSubmit = async (data) => {
  try {
    if (dialogConfig.isEdit) {
      // 编辑
      await updateStock(data)
      ElMessage.success('编辑成功')
    } else {
      // 添加
      await addStock(data)
      ElMessage.success('添加成功')
    }
    
    // 刷新列表
    getStockList()
    // 关闭对话框
    dialogConfig.visible = false
  } catch (error) {
    console.error('操作失败', error)
    ElMessage.error('操作失败')
  }
}

// 切换到编辑模式
const switchToEdit = () => {
  dialogConfig.title = '编辑库存'
  dialogConfig.isEdit = true
  dialogConfig.isView = false
}

// 初始化
onMounted(async () => {
  await getMedicineList()
  getStockList()
})
</script>

<template>
  <div class="stock-container">
    <el-card shadow="never" class="stock-card">
      <template #header>
        <div class="card-header">
          <h3>药品库存管理</h3>
        </div>
      </template>
      
      <!-- 表格 -->
      <data-table
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :search-fields="searchFields"
        @add="handleAdd"
        @edit="handleEdit"
        @view="handleView"
        @delete="handleDelete"
        @batch-delete="handleBatchDelete"
        @refresh="getStockList"
      />
    </el-card>
    
    <!-- 表单对话框 - 添加/编辑 -->
    <dialog-form
      v-if="!dialogConfig.isView"
      v-model:visible="dialogConfig.visible"
      :title="dialogConfig.title"
      v-model="formData"
      :fields="editFormFields"
      :rules="formRules"
      @submit="handleSubmit"
    />
    
    <!-- 表单对话框 - 查看 -->
    <dialog-form
      v-else
      v-model:visible="dialogConfig.visible"
      :title="dialogConfig.title"
      v-model="formData"
      :fields="viewFormFields"
      :readonly="true"
      :show-confirm-button="false"
      :cancel-button-text="'关闭'"
    >
      <template #lastUpdateTime="{ value }">
        {{ formatDateTime(value) }}
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogConfig.visible = false">关闭</el-button>
          <el-button type="primary" @click="switchToEdit">编辑</el-button>
        </div>
      </template>
    </dialog-form>
  </div>
</template>

<style scoped>
.stock-container {
  height: 100%;
}

.stock-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__body) {
  flex: 1;
  overflow: auto;
  padding: 15px;
}

:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}
</style>